<?php

namespace app\server;

use app\server\HredisServer;
use think\cache\driver\Redis;
use think\facade\Config;
use \think\facade\Db;
use think\facade\Request;
use think\facade\Cache;
use think\facade\Queue;

class H5Server
{
    public $log_id;
    public $log_token;
    protected $app_type;
    protected $adsense;
    protected $redis = null;


    protected function xredis()
    {
//        return app('hredis');
        return new Redis(Config::get('database.redis_config.master'));
    }

    protected function getRedis()
    {
        if ($this->redis === null) {
            $this->redis = app('hredis');
        }
        return $this->redis;
    }

    protected function bredis()
    {
        return $this->getRedis();
    }

    /**
     * 获取目标应用（用于H5落地页，支持跨访问）
     */
    public function getAppCors($log_id, $log_token, $app_type, $adsense)
    {
        $this->log_id = $log_id;
        $this->log_token = $log_token;
        $this->app_type = $app_type;
        $this->adsense = $adsense;
        $request = Request::instance();
        $project = $request->get('project', '');
        $platform = $request->get('platform', 'oceanengine');
        $producer = $request->get('producer', 'all');
        $seting = $this->getSeting($project, $platform, $producer);
        if (!empty($seting)) {
            $origin = $this->ipShield2($seting, $seting['origin'], 'origin');
            $target = explode(',', $seting['target']);
            $seting['target'] = array_key_exists($origin, $target) ? $target[$origin] : '';
            $seting['origin'] = $origin;
        } else {
            $seting['origin'] = $seting['target'] = '';
        }

        return $seting;
    }

    /**
     * 获取客户端设备信息
     * @return array 客户端设备信息
     */
    public function getDevice()
    {
        $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        $left = strpos($user_agent, '(');
        $right = strpos($user_agent, ') ');
        $device_info = substr($user_agent, $left + 1, $right - $left - 1);
        $device = explode(';', $device_info);
        return $device;
    }

    /**
     * 获取客户端IP及地区信息
     * @return array IP及地区信息
     */
    public function getIp()
    {
        $ip_addr = app(IpServer::class)->getRegion();
        return $ip_addr;
    }

    /**
     *  * 获取应用设置参数
     * @return array 应用设置参数
     */
    public function getSeting($project, $platform, $producer)
    {
        // 获取缓存（有缓存的情况）
        $key = $project . '-' . $platform . '-' . $producer;
        $cache = $this->bredis()->get($key);
        if ($cache) {
            $cacheArr = json_decode($cache, true);
            if (!empty($cacheArr)) {
                return $cacheArr;
            }
        }
        // 获取数据（没缓存的情况）
        $seting = find('app_seting', '*', ['project' => $project, 'platform' => $platform, 'producer' => $producer, 'device_os' => 'Android']);
        $this->bredis()->set($key, json_encode($seting));
        return $seting;
    }

    /**
     *  * 获取应用设置参数
     * @return array 应用设置参数
     */
    public function getSetingWx($project,$class)
    {
        // 获取缓存（有缓存的情况）
        $key = $project."_".$class;
        $cache = $this->bredis()->get($key);
        if ($cache) {
            $cacheArr = json_decode($cache, true);
            if (!empty($cacheArr)) {
                return $cacheArr;
            }
        }
        $find = find('app_seting_wx','id',['project'=>$project]);
        // 获取数据（没缓存的情况）
        $list = simlist('app_wx_position', 'origin,seting_id,class,ad_img,location,appid,jump_page,webview_url', ['seting_id' => $find['id'], 'class' => $class]);
        app('hredis')->set($key, json_encode($list));
        return $list;
    }

    function ipShield2($seting, $switch_value, $switch_name = '')
    {
        //【origin开启】
        //地区黑名单 + referer无值：origin=1(0)  blacklist
        //地区白名单 + referer无值：origin=1(1)  w
        //地区黑名单 + referer有值（域名匹配）：origin=1(0)  blacklist
        //地区白名单 + referer有值（域名匹配）：origin=1(1)  w  bess.bytedance.net(0)
        //地区黑名单 + referer有值（域名不匹配）：origin=1(0)  blacklist
        //地区白名单 + referer有值（域名不匹配）：origin=1(1)  w
        //【origin关闭】origin=0(0)
//        global $db;
//        global $log_id;
//        global $log_token;
//        global $app_type;
        $time1 = microtime(true);

//        $ip = $this->ipCheck($this->getIp());
        $ip = $this->getIp();
        $region = explode('|', $ip['region']);
        //$province = explode(',', ''); // 省份黑名单
        //$city = explode(',', '北京,上海,深圳,广州,成都,武汉,重庆'); // 城市黑名单
        $province = explode(',', $seting['province']); // 省份黑名单
        $city = explode(',', $seting['city']); // 城市黑名单
        $domain = explode('|', 'bess.bytedance.net|ad.oceanengine.com'); // 间接来源黑名单
        $http_referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : ''; // 直接来源
        $client_referer = isset($_REQUEST['referer']) ? urldecode($_REQUEST['referer']) : ''; // 间接来源
        if ($switch_value == '1') {
            // 对开关做地区屏蔽（审核人员所在地区）
            if ($region[0] != '中国' || $region[2] == '0' || $region[2] == '香港' || $region[2] == '台湾' || in_array($region[2], $province) || in_array($region[3], $city)) {
                $switch = '0';
                $operate = $switch_name . '=' . $switch_value . "  blacklist($switch)";
            } else {
                $switch = '1';
                $operate = $switch_name . '=' . $switch_value . "  w($switch)";
            }
            // 对间接来源做屏蔽（审核人员通过巨量后台直接访问H5落地页）
            if ($switch == '1') {
                $exists_status = false;
                $exists_domain = '';
                foreach ($domain as $val) {
                    if (strExists($val, $client_referer)) {
                        $exists_status = true;
                        $exists_domain = $val;
                    }
                }
                if ($exists_status) {
                    $switch = '0';
                    $operate .= "  $exists_domain($switch)";
                }
            }
            // 对直接来源做屏蔽（审核人员通过抖音等APP模拟预览进入H5落地页）
            if ($switch == '1') {
                if (strExists('packages', $http_referer) && !strExists('clickid', $http_referer)) {
                    $switch = '0';
                    $operate .= "  packages($switch)";
                }
            }
            // 对直接来源做屏蔽（投放计划学习期或开发人员通过巨量后台联调预览进入H5落地页）
            if ($switch == '1') {
                if (strExists('__CLICKID__', $http_referer)) {
                    $switch = '0';
                    $operate .= "  clickid($switch)";
                }
            }
            if ($switch == '1') {
                if (strExists('__AID__', $http_referer)) {
                    $switch = '0';
                    $operate .= "  adid($switch)";
                }
            }
        } else {
            $switch = $switch_value;
        }

        return $switch;
    }


    /* 函数区 */

    /**
     * 无法识别地区检查
     * @param array $ip IP及地区信息
     * @return string IP及地区信息
     */
    public function ipCheck($ip)
    {
        //$ip['remote_addr'] = '117.136.23.12';
        $ip['region'] = '中国|0|福建|未知|未知';
        $region_unknown = $ip['region'] ?? '';
        $region = explode('|', $region_unknown);
        // 无法识别的地区处理（例：中国|0|0|0|移动，中国|0|湖南|0|移动）
        if (empty($region[3])) {
            // 查询本地IP地址库
            $ip_local = find('app_ip_addr', 'region', ['remote_addr' => $ip['remote_addr']]);
            if ($ip_local) {
                // 存在，直接返回
                $ip['http_via'] = $region_unknown;
                $ip['region'] = $ip_local['region'];
            } else {
                // 不存在，获取接口数据
                $response = curlData('https://apidatav2.chinaz.com/ipapi/district?key=a64b38cac3c34393b5951e8479a5f9ab&ip=' . $ip['remote_addr']);
                $data = json_decode($response, true);
                if (isset($data)) {
                    if ($data['StateCode'] == 1) {
                        $result = $data['Result']['data'];
                        $region_new = ($result['country'] ? $result['country'] : '0') . '|0|'
                            . ($result['prov'] ? str_replace('省', '', $result['prov']) : '0') . '|'
                            . ($result['city'] ? str_replace('市', '', $result['city']) : '0') . '|'
                            . ($result['isp'] ? $result['isp'] : '0');
                        $ip['http_via'] = $region_unknown;
                        $ip['region'] = $region_new;
                        // 写入本地IP地址库
                        $params = array(
                            'remote_addr' => $ip['remote_addr'],
                            'region_unknown' => $region_unknown,
                            'region' => $region_new
                        );
//                        $db->insert($params, 'ip_addr');
                        add('app_ip_addr', $params);
                    }
                }
            }
        }
        return $ip;
    }

}


?>
